<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/** Users models **/
class Users extends CI_Model {
	private $users    = 'sys_user';
	private $employee = 'employee';
    private $groups   = 'groups';
	private $acl   	  = 'acl';
	private $log      = 'sys_session';
    
	function checkUserLogin($ID,$password)
    {
        $sql = "SELECT * 
                FROM ".$this->employee."
                JOIN ".$this->users." ON ".$this->users.".employee_id=".$this->employee.".employee_id
                WHERE EmployeeID=".trim($ID)." 
                AND PassText='".$password."'";
                
        $Q=$this->db->query($sql);
		if($Q->num_rows()>0)
			return true;
		return false;	
	}
	
	function getEmployee($ID)
    {
        $sql = "SELECT * 
                FROM ".$this->employee."
                JOIN ".$this->users." ON ".$this->users.".employee_id=".$this->employee.".employee_id
                WHERE user_active=".$ID;
		$sql.= " GROUP BY EmployeeID ";
		$sql.= " ORDER BY EmployeeFirstName ASC";		
        $Q=$this->db->query($sql);
		if($Q->num_rows()>0)
			return $Q->result_array();
		return false;	
	}
	
	function getUserData($ID)
	{
		$sql = "SELECT * 
                FROM ".$this->employee."
                JOIN ".$this->users." ON ".$this->users.".employee_id=".$this->employee.".employee_id
				JOIN ".$this->acl." ON ".$this->acl.".acl=".$this->users.".acl
                WHERE EmployeeID=".trim($ID);
        $Q=$this->db->query($sql);        
		return $Q->row_array();
	}
	
	function updateProfile($image=''){
		$value =  array( 'EmployeeFirstName'  	=>  $this->input->post('name'));
		if(!empty($image))
			$value['EmployeeAvatar'] = $image;	
		$this->db->where('EmployeeID',$this->input->post('id'));				 
		$this->db->update($this->employee,$value);				 
	}
	
	function userLog($ip,$activity){
		$value =  array('ip_address'	=> $ip,
						'session_date'	=> date('Y-m-d H:i:s'),	
						'user_agent'	=> $this->session->userdata('user_login'),
						'last_activity'	=> $activity,
						'user_data'     => $this->db->last_query());
		$this->db->insert($this->log,$value);				
	}
	
	function getUserLog($date=''){
		$sql = "SELECT e.EmployeeID, e.EmployeeFirstName, l.ip_address, DATE_FORMAT(l.session_date, '%d-%m-%Y %H:%i:%s') AS my_date 
		        FROM (sys_session l) 
				INNER JOIN employee e ON e.EmployeeID=l.user_agent";
		if($date)
			$sql .= " WHERE DATE_FORMAT(l.session_date,'%d-%m-%Y')='".$date."'";
		$Q=$this->db->query($sql);
		return $Q->result_array();
	}
    
}